<?php
namespace services;
use addons\epay\library\Service;
require_once(VENDOR_PATH . 'Yop-Sdk/autoload.php');
class YopService{
    public $MerchantNo = '10090775063';
    public function __construct() {
        $sdkConfigFile = VENDOR_PATH."Yop-Sdk/yop_sdk_config_default.json";
        $this->api_client = \Yeepay\Yop\Sdk\Service\Aggpay\AggpayClientBuilder::builder($sdkConfigFile)->build();
    }
    /**
     * 聚合支付统一下单(/rest/v1.0/aggpay/pre-pay)
     *
     * @test
     */
    public function prePay($channel,$pay_way,$order_id,$rebate_amt,$openid,$ip,$divide_detail,$amount)
    {
        // $divide = ['amount'=>$amount,'ledgerNo'=>$this->MerchantNo,'divideDetailDesc'=>'商家支付账单平台收入'];
        // $divide_detail[] = $divide;
        $notifyurl = config('domain') . '/index/notify/notifyurl';
        $returnurl = config('domain') . '/index/notify/returnurl';
        $dividenotifyurl = config('domain') . '/index/notify/dividenotifyurl';
        $request = new \Yeepay\Yop\Sdk\Service\Aggpay\Model\PrePayRequest();

        $request->setParentMerchantNo($this->MerchantNo);
        $request->setMerchantNo($this->MerchantNo);
        $request->setOrderId($order_id);
        $request->setOrderAmount($rebate_amt);
        $request->setExpiredTime(date('Y-m-d H:i:s',time()+2592000));
        $request->setNotifyUrl($notifyurl);
        $request->setRedirectUrl($returnurl);
        $request->setMemo("商家支付账单");
        $request->setGoodsName("商家支付账单");
        $request->setFundProcessType("REAL_TIME");//REAL_TIME:不需要分账,REAL_TIME_DIVIDE:实时分账;需同时传入divideDetail
        $request->setPayWay($pay_way);
        $request->setChannel($channel);
        $request->setScene("OFFLINE");
        $request->setAppId(config('jmgzh.appid'));
        if ($openid) {
            $request->setUserId($openid);
        }
        $request->setUserIp($ip);
        // $request->setChannelSpecifiedInfo("{\"hbFqNum\":\"3\",\"hbFqSellerPercent\":\"0\",\"sysServiceProviderId\":\"\"}");
        // $request->setChannelPromotionInfo("channelPromotionInfo_example");
        // $request->setIdentityInfo("{\"identityVerifyType\":\"Y\",\"payerIdType\":\"IDENTITY_CARD\",\"payerNumber\":\"234512198006252456\",\"payerName\":\"名字\"}");
        // $request->setLimitCredit("N");
        // $request->setToken("83BCDF29CFACB4411533080B67864EF8C907CCDC5E10A707C285FEA10CDB8221");
        // $request->setUniqueOrderNo("1012202101070000001989946571");
        // $request->setCsUrl("csUrl_example");
        // $request->setAccountLinkInfo("{accountProvider\":\"BOL\",\"token\":\"xxx\"}");
        // $request->setYpPromotionInfo("自定义支付立减：[{\"amount\":\"0.01\",\"type\":\"CUSTOM_REDUCTION\"}],自定义补贴商户[{\"type\":\"CUSTOM_ALLOWANCE\"}]");
        // $request->setBankCode("BOC");
        // $request->setBusinessInfo("businessInfo_example");
        // $request->setUserAuthCode("userAuthCode_example");
        // $request->setChannelActivityInfo("channelActivityInfo_example");
        // $request->setTerminalId("terminalId_example");
        // $request->setTerminalSceneInfo("{\"storeId\":\"门店id\",\"storeName\":\"门店名称\",\"operatorId\":\"商户操作员编号\",\"alipayStoreId\":\"支付宝的店铺编号\",\"areaCode\":\"门店行政区划码\",\"address\":\"门店详细地址\"}");
        // $request->setYpAccountBookNo("ypAccountBookNo_example");
        // $request->setTerminalInfo("{\"shopName\":\"网点名称\",\"shopCustomerNumber\":\"网点编号\"}");
        // $request->setProductInfo("[{\"id\":\"random_reduction_pro\"}]");
        // $request->setDivideDetail(json_encode($divide_detail,JSON_UNESCAPED_UNICODE));
        // $request->setDivideNotifyUrl($dividenotifyurl);
        // $request->setFeeSubsidyInfo("[{\"subsidyMerchantNo\":\"10080009498\",\"subsidyAccountType\":\"FEE_ACCOUNT\",\"subsidyType\":\"ABSOLUTE\",\"subsidyProportion\":\"\",\"subsidyCalculateType\":\"SINGLE_PERCENT\",\"subsidyPercentFee\":\"0.6\",\"subsidyFixedFee\":\"\",\"subsidySingleMaxFee\":\"\"}]");
        // $request->setAgreementId("agreementId_example");
        // $request->setCreditOrderId("creditOrderId_example");
        try{
            $response = $this->api_client->prePay($request);
            $result = $response->getResult();
            return $result['prePayTn'];
        }catch (\Exception $e) {
            echo 'Exception when calling AggpayClient->prePay: ', $e->getMessage(), PHP_EOL;
        }
    }
    /**
     * 查询渠道报备信息(/rest/v1.0/aggpay/report/query)
     *
     * @test
     */
    public function agg_report_query_v1_0Test()
    {
        $sdkConfigFile = VENDOR_PATH."Yop-Sdk/yop_sdk_config_default.json";
        $this->api_client = \Yeepay\Yop\Sdk\Service\Aggpay\AggpayClientBuilder::builder($sdkConfigFile)->build();
        $request = new \Yeepay\Yop\Sdk\Service\Aggpay\Model\AggReportQueryV10Request();

        $request->setParentMerchantNo($this->MerchantNo);
        $request->setMerchantNo($this->MerchantNo);
        $request->setChannel("ALIPAY");
        $request->setChannelNo("2088421851350050");
        $request->setScene("OFFLINE");
        // $request->setPromotionType("promotionType_example");
        // $request->setDataRange("dataRange_example");
        try{
            $response = $this->api_client->agg_report_query_v1_0($request);
            print_r($response->getResult());
        }catch (\Exception $e) {
            echo 'Exception when calling AggpayClient->agg_report_query_v1_0: ', $e->getMessage(), PHP_EOL;
        }
    }
    /**
     * 商户授权状态查询接口(/rest/v2.0/mer/auth/state/query)
     *
     * @test
     */
    public function authStateQueryV2Test()
    {
        $sdkConfigFile = VENDOR_PATH."Yop-Sdk/yop_sdk_config_default.json";
        $this->api_client = \Yeepay\Yop\Sdk\Service\Mer\MerClientBuilder::builder($sdkConfigFile)->build();
        $request = new \Yeepay\Yop\Sdk\Service\Mer\Model\AuthStateQueryV2Request();

        $request->setMerchantNo($this->MerchantNo);
        try{
            $response = $this->api_client->authStateQueryV2($request);
            print_r($response->getResult());
        }catch (\Exception $e) {
            echo 'Exception when calling MerClient->authStateQueryV2: ', $e->getMessage(), PHP_EOL;
        }
    }
    /**
     * 公众号配置接口(/rest/v2.0/aggpay/wechat-config/add)
     *
     * @test
     */
    public function wechatConfigAddV2Test()
    {
        $sdkConfigFile = VENDOR_PATH."Yop-Sdk/yop_sdk_config_default.json";
        $this->api_client = \Yeepay\Yop\Sdk\Service\Aggpay\AggpayClientBuilder::builder($sdkConfigFile)->build();
        $request = new \Yeepay\Yop\Sdk\Service\Aggpay\Model\WechatConfigAddV2Request();

        $request->setParentMerchantNo($this->MerchantNo);
        $request->setMerchantNo($this->MerchantNo);
        $request->setTradeAuthDirList("[\"https://bdbbill.chbcplus.com/\",\"https://cash.yeepay.com/newwap/\",\"https://shouyin.yeepay.com/nc-cashier-wap/\"]");
        $request->setAppIdList("[{\"appId\":\"wx467aa6d85fa63c7c\",\"appSecret\":\"60afeaad1f7ba486c83f8fef17e0eaab\",\"appIdType\":\"OFFICIAL_ACCOUNT\"}]");
        // $request->setReportMerchantNo("reportMerchantNo_example");
        try{
            $response = $this->api_client->wechatConfigAddV2($request);
            print_r($response->getResult());
        }catch (\Exception $e) {
            echo 'Exception when calling AggpayClient->wechatConfigAddV2: ', $e->getMessage(), PHP_EOL;
        }
    }
    /**
     * 公众号配置查询(/rest/v2.0/aggpay/wechat-config/query)
     *
     * @test
     */
    public function wechatConfigQueryV2Test()
    {
        $sdkConfigFile = VENDOR_PATH."Yop-Sdk/yop_sdk_config_default.json";
        $this->api_client = \Yeepay\Yop\Sdk\Service\Aggpay\AggpayClientBuilder::builder($sdkConfigFile)->build();
        $request = new \Yeepay\Yop\Sdk\Service\Aggpay\Model\WechatConfigQueryV2Request();

        $request->setParentMerchantNo($this->MerchantNo);
        $request->setMerchantNo($this->MerchantNo);
        try{
            $response = $this->api_client->wechatConfigQueryV2($request);
            $obj = $response->getResult();
            print_r(json_encode($obj['configResult'],JSON_UNESCAPED_UNICODE));
        }catch (\Exception $e) {
            echo 'Exception when calling AggpayClient->wechatConfigQueryV2: ', $e->getMessage(), PHP_EOL;
        }
    }

    /**
     * 解密数字信封
     * @param $source 待解密内容
     * @param $private_Key 商户私钥（用于解密）
     * @param $public_Key 平台公钥(用于签名)
     * @return string 已解密内容
     * nitify解出来：
        {"orderId":"806574329430","bankOrderId":"5898064243241207","channel":"WECHAT","payWay":"WECHAT_OFFIACCOUNT","memo":"memo_example","uniqueOrderNo":"1013202412070000016533893179","merchantName":"俱美科技","orderAmount":"0.01","payAmount":"0.01","realPayAmount":"0.01","tradeType":"REALTIME","channelOrderId":"4200002518202412074360021050","paySuccessDate":"2024-12-07 16:05:00","outClearChannel":"UP","payerInfo":"{\"appID\":\"wx4be2139dd6bfea5b\",\"bankCardNo\":\"\",\"bankId\":\"CFT\",\"cardType\":\"DEBIT\",\"channelTrxId\":\"4200002518202412074360021050\",\"mobilePhoneNo\":\"\",\"userID\":\"oJaTf6wG74N9oWSdR_EZN09yZzOE\"}","appID":"wx4be2139dd6bfea5b","parentMerchantNo":"10090775063","channelTrxId":"4200002518202412074360021050","merchantNo":"10090775063","status":"SUCCESS"}
        devidenotify解出来：
        {"divideStatus":"SUCCESS","orderId":"806574329430","bizSystemNo":"AGG_PAY","parentMerchantNo":"10090775063","uniqueOrderNo":"1013202412070000016533893179","divideRequestId":"806574329430","divideDetail":"[{\"amount\":0.01,\"divideDetailNo\":\"1010202412070000016533895935\",\"ledgerType\":\"MERCHANT2MERCHANT\",\"invoice\":\"FALSE\",\"divideDetailDesc\":\"商家支付账单平台收入\",\"ledgerNo\":\"10090775063\"}]","merchantNo":"10090775063","createDate":"2024-12-07 16:05:00","divideSuccessDate":"2024-12-07 16:05:00"}
     */
    public static function decrypt($source, $private_Key, $public_Key)
    {
        $YopSignUtils = new \Yeepay\Yop\Sdk\Utils\YopSignUtils();
        return $YopSignUtils->decrypt($source, $private_Key, $public_Key);
    }
    /**
     * 集团账户资金划拨(/rest/v1.0/account/group/account/transfer)
     *
     * @test
     */
    public function groupAccountTransferTest()
    {
        $sdkConfigFile = VENDOR_PATH."Yop-Sdk/yop_sdk_config_default.json";
        $this->api_client = \Yeepay\Yop\Sdk\Service\Account\AccountClientBuilder::builder($sdkConfigFile)->build();
        $request = new \Yeepay\Yop\Sdk\Service\Account\Model\GroupAccountTransferRequest();

        $request->setParentMerchantNo($this->MerchantNo);
        $request->setRequestNo("TRANS121332131241");
        $request->setFromMerchantNo($this->MerchantNo);
        $request->setToMerchantNo("10090782047");
        $request->setOrderAmount("0.01");
        $request->setUsage("withdrawal");
        $request->setFeeChargeSide("OUTSIDE");
        // $request->setNotifyUrl("notifyUrl_example");
        try{
            $response = $this->api_client->groupAccountTransfer($request);
            print_r($response->getResult());
        }catch (\Exception $e) {
            echo 'Exception when calling AccountClient->groupAccountTransfer: ', $e->getMessage(), PHP_EOL;
        }
    }
    /**
     * 申请余额分账(/rest/v1.0/divide/balance/apply)
     *
     * @test
     */
    public function balanceApply($sn,$divideDetail)
    {
        $sdkConfigFile = VENDOR_PATH."Yop-Sdk/yop_sdk_config_default.json";
        $this->api_client = \Yeepay\Yop\Sdk\Service\Divide\DivideClientBuilder::builder($sdkConfigFile)->build();
        $request = new \Yeepay\Yop\Sdk\Service\Divide\Model\BalanceApplyRequest();

        $batchnotifyurl = config('domain') . '/index/notify/batchnotifyurl';
        $request->setParentMerchantNo($this->MerchantNo);
        $request->setMerchantNo($this->MerchantNo);
        $request->setDivideRequestId($sn);
        $request->setDivideDetail($divideDetail);
        $request->setBatchNotifyUrl($batchnotifyurl);
        try{
            $response = $this->api_client->balanceApply($request);
            $result = $response->getResult();
            return $result;
        }catch (\Exception $e) {
            echo 'Exception when calling DivideClient->balanceApply: ', $e->getMessage(), PHP_EOL;
        }
    }
    /**
     * 查询余额分账结果(/rest/v1.0/divide/balance/query)
     *
     * @test
     */
    public function balanceQueryTest()
    {
        $sdkConfigFile = VENDOR_PATH."Yop-Sdk/yop_sdk_config_default.json";
        $this->api_client = \Yeepay\Yop\Sdk\Service\Divide\DivideClientBuilder::builder($sdkConfigFile)->build();
        $request = new \Yeepay\Yop\Sdk\Service\Divide\Model\BalanceQueryRequest();

        $request->setDivideRequestId("34536466512");
        $request->setMerchantNo($this->MerchantNo);
        try{
            $response = $this->api_client->balanceQuery($request);
            print_r($response->getResult());
        }catch (\Exception $e) {
            echo 'Exception when calling DivideClient->balanceQuery: ', $e->getMessage(), PHP_EOL;
        }
    }
    /**
     * 转账到微信零钱-下单
     *
     * @test
     */
    public function transferWechat($no,$amount,$openid,$remark,$username='')
    {
        $sdkConfigFile = VENDOR_PATH."Yop-Sdk/yop_sdk_config_default.json";
        $api_client = \Yeepay\Yop\Sdk\Service\Account\AccountClientBuilder::builder($sdkConfigFile)->build();
        $request = new \Yeepay\Yop\Sdk\Service\Account\Model\TransferWechatOrderRequest();
        $notifyurl = config('domain') . '/index/notify/txnotify';
        $request->setRequestNo($no);
        $request->setMerchantNo($this->MerchantNo);
        $request->setAmount($amount);
        $request->setAppId(config('jmgzh.appid'));
        $request->setScene("JSAPI");
        $request->setOpenId($openid);
        if ($username) {
            $request->setUserName($username);
        }
        $request->setRemark($remark);
        $request->setNotifyUrl($notifyurl);
        $request->setParentMerchantNo($this->MerchantNo);

        try {
            $response = $api_client->transferWechatOrder($request);
            $result = $response->getResult();
            return $result;
        }catch (\Exception $e) {
            echo 'Exception when calling AccountClient->transferWechatOrder: ', $e->getMessage(), PHP_EOL;
        }
    }

}
